<template>
  <div id="assessdetail">
    <el-dialog title="设置类型" :visible.sync="settingVisible" width="1000px" :close-on-click-modal="false" :close-on-press-escape="false" append-to-body>
      <el-form :model="classForm" label-width="100px" ref="classForm" :inline="true">
        <el-form-item label="类型" prop="label" :rules="{ required: true, message: '必填', trigger: 'blur' }">
          <el-input v-model="classForm.label" style="width:220px"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="addDic()" type="success">添加</el-button>
        </el-form-item>
      </el-form>
      <section class="wboxd">
        <el-table :data="workTypeList" highlight-current-row style="width: 100%;" border class="settingDicTable">
          <!-- <el-table-column prop="value" label="编号">
          </el-table-column> -->
          <el-table-column prop="label" label="类型">
          </el-table-column>
          <el-table-column label="状态">
            <template slot-scope="scope">
              <span v-html="dicDeleted(scope.row.deleted)"></span>
            </template>
          </el-table-column>
          <el-table-column label="调整顺序" width="150">
            <template slot-scope="scope">
              <el-button slot="reference"  type="text" :disabled="moveloading" icon="el-icon-caret-top" @click="moveDic(scope.row.value,true)" v-if="scope.$index!==0" style="float:left">上移</el-button>
              <el-button slot="reference"  type="text" :disabled="moveloading" icon="el-icon-caret-bottom" @click="moveDic(scope.row.value,false)" v-if="scope.$index!==workTypeList.length-1" style="float:right">下移</el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template slot-scope="scope">
              <el-popconfirm title="确定停用该类型吗？" v-if="!scope.row.deleted" @confirm="stopDic(scope.row.value)">
                <el-button slot="reference" type="text" icon="el-icon-warning">停用</el-button>
              </el-popconfirm>
              <el-popconfirm title="确定启用该类型吗？" v-if="scope.row.deleted" @confirm="startDic(scope.row.value)">
                <el-button slot="reference"  type="text" icon="el-icon-success">启用</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </section>
    </el-dialog>
    <el-form :model="editForm" label-width="200px" ref="editForm" :inline="true" style="padding:10px 0 0;clear:both" v-if="!pageLoading" :rules="editFormRules">
      <el-row>
          <table cellspacing="0" cellpadding="0" class="mytable">
            <tr>
              <th style="width:120px">类型</th>
              <td>
                <template v-if="readOnly">{{editForm.workType}}</template>
                <el-form-item prop="workType" v-else>
                  <el-select v-model="editForm.workType" placeholder="请选择">
                    <el-option v-for="(item,index) in workTypeList.filter(item=>item.deleted===0)" :key="index" :label="item.label" :value="item.label"></el-option>
                  </el-select>
                  <el-tooltip class="item" effect="dark" content="设置类型" placement="top" v-if="isWorkRecordAdmin">
                    <el-button circle type="success" @click="setupType()" icon="el-icon-setting"></el-button>
                  </el-tooltip>
                </el-form-item>
              </td>
            </tr>
            <tr>
              <th style="width:120px">工作事项</th>
              <td>
                <template v-if="readOnly">{{editForm.workPlan}}</template>
                <el-form-item prop="workPlan" v-else>
                  <el-input v-model="editForm.workPlan" style="width:800px" maxlength="200"></el-input>
                </el-form-item>
              </td>
            </tr>
            <tr>
              <th>主要任务</th>
              <td>
                <div v-if="readOnly" v-html="editForm.content.replace(/\n/g,'<br>')"></div>
                <el-form-item v-else prop="content">
                  <el-input type="textarea" v-model="editForm.content" style="width:800px;" rows="5" maxlength="1000" show-word-limit></el-input>
                </el-form-item>
              </td>
            </tr>
            <tr>
              <th>责任处室</th>
              <td>
                <template>{{editForm.respDept==='司领导'?'':editForm.respDept}}</template>
              </td>
            </tr>
            <tr>
              <th>责任人</th>
              <td>
                <!--查看时或当前用户为处内人员（非授权工作日志管理员）时只能查看-->
                <template v-if="readOnly||(myRole===1&&!isAdmin&&!isDown)">{{editForm.respUserName}}</template>
                <template v-else>
                  <!--下发时可选副司长和处长-->

                  <el-form-item prop="respUserId1" key="respUserId1" v-if="isDown">
                    <el-select v-model="editForm.respUserId" placeholder="请选择" @change="checkRespUserRole">
                      <el-option v-for="item in leaderList" :key="item.userId" :label="item.userName" :value="item.userId"></el-option>
                      <el-option v-for="item in unitList" :key="item.userId" :label="item.userName" :value="item.userId"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item prop="respUserId2" key="respUserId2" v-else>
                    <!--综合处处长或授权工作日志管理员可从所有人员中复选-->
                    <el-select v-if="isAdmin" placeholder="请选择" style="width:800px"
                      v-model="adminRespUsers"
                      @change="changeAdminRespUsers"
                      multiple
                      filterable>
                      <el-option-group
                        v-for="(group,index) in allUser"
                        :key="index"
                        :label="group.label">
                        <el-option
                          v-for="(item,subindex) in group.options"
                          :key="subindex"
                          :label="item.label"
                          :value="item.value">
                        </el-option>
                      </el-option-group>
                    </el-select>
                    <!--副司长从管理处室、干部处处长从本处单选责任人-->
                    <el-select v-model="editForm.respUserId" placeholder="请选择" @change="changeRespUser" v-else>
                      <el-option v-for="(item,index) in personList" :key="index" :label="myRole<3?item.truename:item.truename+'（'+item.unitname+'）'" :value="item.id"></el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </td>
            </tr>
            <!--综合处处长或授权工作日志管理员可从所有人员中复选，如选择多个人员，可以选出其中一人为主要责任人-->
            <tr v-if="isAdmin&&adminRespUsers.length>1">
              <th>主要责任人</th>
              <td>
                <template>
                  <!-- {{adminRespUsers}} -->
                  <el-radio-group v-model="editForm.respUserId" @change="changeMainRespUser">
                    <el-radio :label="-1">无</el-radio>
                    <el-radio v-for="item in adminRespUsers" :label="item" :key="item">{{userId2Name(item)}}</el-radio>
                  </el-radio-group>
                </template>
              </td>
            </tr>
            <!--下发时如果责任人选择的是司领导，可以在处长中选择其他责任人-->
            <tr v-if="editForm.respDept==='司领导'&&!isAdmin">
              <th>其他责任人</th>
              <td>
                <!--查看时，且当前用户不是责任人（主管副司长）只能查看其他责任人列表-->
                <template v-if="readOnly&&editForm.respUserId!==myUserId">
                  <table style="border-left:1px solid #74a6cc;border-top:1px solid #74a6cc;border-collapse:collapse" v-if="editForm.respUsers&&editForm.respUsers.length>0">
                    <tr><th style="text-align:center">姓名</th><th style="text-align:center">部门</th><th style="text-align:center">完成情况</th><th style="text-align:center">完成时间</th></tr>
                    <tr v-for="(item,index) in editForm.respUsers" :key="index"><td>{{item.respUserName}}</td><td>{{item.respDept}}</td><td>{{completeStatusText(item.completeStatus)}}</td><td>{{item.completeTime}}</td></tr>
                  </table>
                </template>
                <template v-else>
                  <!--查看时，且当前用户是责任人（主管副司长），可以进查看其他责任人，或者增加修改其他责任人-->
                  <template v-if="readOnly">
                    <table style="border-left:1px solid #74a6cc;border-top:1px solid #74a6cc;border-collapse:collapse;margin-bottom:10px;" v-if="editForm.respUsers&&editForm.respUsers.length>0">
                      <tr><th style="text-align:center">姓名</th><th style="text-align:center">部门</th><th style="text-align:center">完成情况</th><th style="text-align:center">完成时间</th></tr>
                      <tr v-for="(item,index) in editForm.respUsers" :key="index"><td>{{item.respUserName}}</td><td>{{item.respDept}}</td><td>{{completeStatusText(item.completeStatus)}}</td><td>{{item.completeTime}}</td></tr>
                    </table>
                  </template>
                  <!--查看时或编辑时，当前用户为综合处处长或授权工作日志管理员，可增加修改其他责任人（下拉复选形式）-->
                  <el-form-item prop="respUserId">
                    <el-select v-model="editForm.otherRespUserIds" placeholder="请选择" multiple @change="$forceUpdate()" style="width:400px">
                      <el-option v-for="item in unitList" :key="item.userId" :label="item.userName" :value="item.userId"></el-option>
                    </el-select>
                  </el-form-item>
                  <!--查看时，且当前用户是责任人（主管副司长），可以进查看其他责任人，或者增加修改其他责任人，显示更改保存按钮-->
                  <template v-if="readOnly">
                    <el-button type="primary" @click.native="modOtherRespUserIds()" :loading="saveloading" style="margin-left:20px;">更改其他责任人</el-button>
                  </template>
                </template>
              </td>
            </tr>
            <!--下发时，如果查看，只显示其他责任人列表，不能编辑-->
            <template v-else>
            <tr v-if="readOnly&&editForm.respUsers&&editForm.respUsers.length>0">
              <th>其他责任人</th>
              <td>
                <table style="border-left:1px solid #74a6cc;border-top:1px solid #74a6cc;border-collapse:collapse">
                  <tr><th style="text-align:center">姓名</th><th style="text-align:center">部门</th><th style="text-align:center">完成情况</th><th style="text-align:center">完成时间</th></tr>
                  <tr v-for="(item,index) in editForm.respUsers" :key="index"><td>{{item.respUserName}}</td><td>{{item.respDept}}</td><td>{{completeStatusText(item.completeStatus)}}</td><td>{{item.completeTime}}</td></tr>
                </table>
              </td>
            </tr>
            </template>
            <tr>
              <th>预计完成时限</th>
              <td>
                <template v-if="readOnly"> {{editForm.endDate}}</template>
                <el-form-item prop="endDate" v-else>
                  <el-date-picker
                    v-model="editForm.endDate"
                    type="date"
                    align="right"
                    value-format="yyyy-MM-dd">
                  </el-date-picker>
                </el-form-item>
              </td>
            </tr>
            <tr>
              <th>备注</th>
              <td>
                <div v-if="readOnly" v-html="editForm.remarks.replace(/\n/g,'<br>')"></div>
                <el-form-item v-else prop="remarks">
                  <el-input type="textarea" v-model="editForm.remarks" style="width:800px" rows="2"></el-input>
                </el-form-item>
              </td>
            </tr>
          </table>
          <template v-if="!readOnly">
            <el-button type="primary" @click.native="editFormSubmit()" :loading="saveloading" style="margin-left:20px;">提交</el-button>
          </template>
      </el-row>
    </el-form>
  </div>
</template>

<script>
export default {
  watch: {
    timestamp: {
      handler (val) {
        // this.$refs['editForm'].resetFields()
        this.init()
      },
      immediate: true
    },
    filterText (val) {
      this.$refs.tree.filter(val)
    }
  },
  props: {
    // 综合处处长或授权管理员从allList中调用本界面时，参数下发isDown和isAdmin互斥
    isAdmin: false,
    isDown: false,
    timestamp: '',
    projectId: null,
    readOnly: false,
    showUnit: false
  },
  data () {
    return {
      allUserList: [],
      adminRespUsers: [],
      allUser: [],
      isWorkRecordAdmin: false,
      myUserId: 0,
      moveloading: false,
      settingVisible: false,
      classForm: {},
      myRole: 0,
      workTypeList: [],
      selectAllBtn: true,
      filterText: '',
      treedata: [],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      pageLoading: true,
      saveloading: false,
      editForm: {
        id: null,
        beginDate: '',
        endDate: '',
        workPlan: '',
        workType: '',
        content: '',
        respDept: '',
        respUserId: null,
        respUserName: '',
        otherRespUserIds: [],
        remarks: ''
      },
      unitList: [],
      leaderList: [],
      editFormRules: {
        workType: [
          { required: true, message: '必填项', trigger: 'change' }
        ],
        workPlan: [
          { required: true, message: '必填项', trigger: 'change' }
        ],
        content: [
          { required: true, message: '必填项', trigger: 'change' }
        ],
        endDate: [
          { required: true, message: '必填项', trigger: 'change' }
        ]
      },
      personList: [],
      unitName: ''
    }
  },
  methods: {
    userId2Name (id) {
      return this.allUserList.find(item => item.id === id).truename
    },
    changeAdminRespUsers () {
      if (this.adminRespUsers.length !== 1) {
        this.editForm.respDept = ''
        this.editForm.respUserId = -1
        this.editForm.respUserName = ''
      } else {
        this.editForm.respUserId = this.adminRespUsers[0]
        this.editForm.respUserName = this.allUserList.find(item => item.id === this.adminRespUsers[0]).truename
        this.editForm.respDept = this.allUserList.find(item => item.id === this.adminRespUsers[0]).unitname
      }
    },
    changeMainRespUser () {
      if (this.editForm.respUserId === -1) {
        this.editForm.respUserName = ''
        this.editForm.respDept = ''
      } else {
        this.editForm.respUserName = this.allUserList.find(item => item.id === this.editForm.respUserId).truename
        this.editForm.respDept = this.allUserList.find(item => item.id === this.editForm.respUserId).unitname
      }
    },
    getAllUser () {
      this.$http
        .get(this.$http.defaults.workRecordAPI + `api/auth/getUsersGroupByUnitname`)
        .then(response => {
          if (response.data.success) {
            this.allUserList = []
            let options = []
            let suboptions = []
            for (let key in response.data.result) {
              suboptions = []
              for (let item of response.data.result[key]) {
                suboptions.push({value: item.id, label: item.truename})
                this.allUserList.push({id: item.id, truename: item.truename, unitname: item.unitname})
              }
              options.push({label: key, options: suboptions})
            }
            this.allUser = options
          } else {
            console.log('获取失败')
          }
        })
        .catch(function (error) {
          console.log(error)
        })
    },
    changeRespUser () {
      if (this.myRole === 3) {
        this.editForm.respDept = this.personList.find(item => item.id === this.editForm.respUserId).unitname
      }
    },
    completeStatusText (status) {
      switch (status) {
        case 1:
          return '未完成'
        case 2:
          return '完成'
        case 3:
          return '结束'
      }
    },
    dicDeleted (flag) {
      return flag ? '<font color=red>已停用</font>' : '<font color=green>已启用</font>'
    },
    startDic (code) {
      this.$http
        .get(this.$http.defaults.workRecordAPI + `api/dict/enableByCode?dictCode=` + code)
        .then(response => {
          if (response.data.success) {
            this.$message({
              message: '操作成功',
              type: 'success'
            })
            this.getDics('01', 'workTypeList')
          } else {
            this.$message({
              message: '操作失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(function () {
          this.$message({
            message: '网络操作失败',
            type: 'error'
          })
        })
    },
    moveDic (code, up) {
      this.moveloading = true
      this.$http
        .get(this.$http.defaults.workRecordAPI + 'api/dict/moveByCode?up=' + up + '&code=' + code)
        .then(response => {
          if (response.data.success) {
            this.getDics('01', 'workTypeList')
          } else {
            this.$message({
              message: '操作失败:' + response.data.message,
              type: 'error'
            })
          }
          this.moveloading = false
        })
        .catch(function () {
          this.$message({
            message: '网络操作失败',
            type: 'error'
          })
        })
    },
    stopDic (code) {
      this.$http
        .get(this.$http.defaults.workRecordAPI + `api/dict/disableByCode?dictCode=` + code)
        .then(response => {
          if (response.data.success) {
            this.$message({
              message: '操作成功',
              type: 'success'
            })
            this.getDics('01', 'workTypeList')
          } else {
            this.$message({
              message: '操作失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(function () {
          this.$message({
            message: '网络操作失败',
            type: 'error'
          })
        })
    },
    addDic () {
      this.$refs.classForm.validate((valid) => {
        if (valid) {
          let para = {
            dictText: this.classForm.label
          }
          this.$http
            .post(this.$http.defaults.workRecordAPI + `api/dict/create`, para)
            .then(response => {
              if (response.data.success) {
                this.$message({
                  message: '提交成功',
                  type: 'success'
                })
                this.getDics('01', 'workTypeList')
                this.classForm.label = ''
              } else {
                this.$message({
                  message: '提交失败:' + response.data.message,
                  type: 'error'
                })
              }
            })
            .catch(function () {
              this.$message({
                message: '网络提交失败',
                type: 'error'
              })
            })
        }
      })
    },
    setupType () {
      this.settingVisible = true
    },
    init () {
      this.editFormReset() // 重置表单

      this.getDeptList()
      if (this.isDown) {
        this.getLeaders()
      } else {
        if (this.isAdmin) {
          this.editForm.respUserId = -1
          this.editForm.respUserName = ''
          this.editForm.respDept = ''
          this.getAllUser()
        } else {
          if (this.myRole === 2) {
            this.getPersons()
          } else if (this.myRole === 3) {
            this.getManagePersons()
          } else {
            if (this.projectId && this.projectId !== '') {
              this.getDetail(this.projectId)
            } else {
              this.pageLoading = false
            }
          }
        }
      }
    },
    checkRespUserRole (val) {
      let myUnit = this.unitList.find(item => item.userId === val)
      if (!myUnit) {
        myUnit = this.leaderList.find(item => item.userId === val)
      }
      console.log(myUnit)
      this.editForm.respDept = myUnit.deptName
      this.editForm.respUserName = myUnit.userName
    },
    changeUnit (val) {
      console.log(this.unitList)
      let myUnit = this.unitList.find(item => item.deptName === val)
      console.log(myUnit)
      this.editForm.respUserId = myUnit.userId
      this.editForm.respUserName = myUnit.userName
    },
    // daterangeChange (e) {
    //   let _this = this
    //   _this.$nextTick(() => {
    //     _this.$forceUpdate()
    //   })
    // },
    getDics (code, listname) {
      this.$http
        .get(this.$http.defaults.workRecordAPI + `api/dict/getByCode?code=` + code)
        .then(response => {
          if (response.data.success) {
            this[listname] = response.data.result
          } else {
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.$message({
            message: '网络获取失败:' + error,
            type: 'error'
          })
        })
    },
    getPersons () {
      let para = {
        unitName: localStorage.getItem('unitName')
      }
      this.$http
        .post(this.$http.defaults.workRecordAPI + `api/record/findUserByIdentityAndUnit`, para)
        .then(response => {
          if (response.data.success) {
            this.personList = response.data.result
            this.editForm.respUserId = this.personList.find(item => item.truename === localStorage.getItem('userTrueName')).id

            if (this.projectId && this.projectId !== '') {
              this.getDetail(this.projectId)
            } else {
              this.pageLoading = false
            }
          } else {
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.$message({
            message: '网络获取失败:' + error,
            type: 'error'
          })
        })
    },
    getManagePersons () {
      this.$http.get(this.$http.defaults.workRecordAPI + `api/record/getManagedep`).then(response => {
        if (response.data.success === true) {
          let manageDep = JSON.parse(response.data.result)
          console.log(manageDep)
          this.personList = []
          manageDep.forEach(item => {
            this.$http
              .post(this.$http.defaults.workRecordAPI + `api/record/findUserByIdentityAndUnit`, {
                unitName: item
              })
              .then(response => {
                if (response.data.success) {
                  this.personList = [...this.personList, ...response.data.result]
                } else {
                  this.$message({
                    message: '获取失败:' + response.data.message,
                    type: 'error'
                  })
                }
              })
              .catch(error => {
                console.log(error)
                this.$message({
                  message: '网络获取失败:' + error,
                  type: 'error'
                })
              })
          })
        } else {
          console.log('获取失败:' + response.data.message)
          this.$message({
            message: '获取失败:' + response.data.message,
            type: 'error'
          })
        }
      })
    },
    getLeaders () {
      let para = {
        userIdentity: 4
      }
      this.$http
        .post(this.$http.defaults.workRecordAPI + `api/record/findUserByIdentityAndUnit`, para)
        .then(response => {
          if (response.data.success) {
            this.leaderList = []
            response.data.result.forEach(item => {
              this.leaderList.push({userId: item.id, deptName: item.unitname, userName: item.truename})
            })
          } else {
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.$message({
            message: '网络获取失败:' + error,
            type: 'error'
          })
        })
    },
    modOtherRespUserIds () {
      let userArr = this.unitList.filter(item => this.editForm.otherRespUserIds.indexOf(item.userId) > -1)
      let arr = []
      userArr.forEach(item => {
        arr.push({respDept: item.deptName, respUserName: item.userName, respUserId: item.userId})
      })
      let otherRespUsers = arr
      let para = {
        id: this.editForm.id,
        respUsers: otherRespUsers,
        hasOtherRespUser: otherRespUsers.length > 0
      }
      this.saveloading = true
      let url = 'api/record/saveRecord'
      this.$http
        .post(this.$http.defaults.workRecordAPI + url, para)
        .then(response => {
          this.saveloading = false
          if (response.data.success) {
            this.editFormReset()
            this.$emit('dialogHide', true)
            this.$message({
              message: '保存成功！',
              type: 'success'
            })
          } else {
            this.$message({
              message: '保存失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          this.saveloading = false
          console.log(error)
          this.$message({
            message: '网络保存失败:' + error,
            type: 'error'
          })
        })
    },
    editFormSubmit (reEnterFlag) {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          // this.saveloading = true
          let respUserName = ''
          if (this.isDown) {
            respUserName = this.editForm.respUserName
            this.$http.get(this.$http.defaults.workRecordAPI + `api/config/getValueByKey?key=report-month`).then(response => {
              if (response.data.success === true) {
                if (response.data.result === '') {
                  let nowDate = new Date()
                  this.editForm.beginDate = this.getFormatDate(new Date(Date.UTC(nowDate.getFullYear(), nowDate.getMonth(), 1)))
                  this.savedata(respUserName)
                } else {
                  this.editForm.beginDate = response.data.result + '-01'
                  this.savedata(respUserName)
                }
              } else {
                console.log('获取失败:' + response.data.message)
                this.$message({
                  message: '获取失败:' + response.data.message,
                  type: 'error'
                })
                return false
              }
            })
          } else {
            if (this.isAdmin) {
              if (this.adminRespUsers.length === 0) {
                this.$message({
                  message: '至少选择一个责任人',
                  type: 'error'
                })
              } else {
                this.$http.get(this.$http.defaults.workRecordAPI + `api/config/getValueByKey?key=report-month`).then(response => {
                  if (response.data.success === true) {
                    if (response.data.result === '') {
                      this.$message({
                        message: '未开启填报！',
                        type: 'error'
                      })
                      // 应增加下发时beginDate处理
                    } else {
                      this.editForm.beginDate = response.data.result + '-01'
                      this.savedata(this.editForm.respUserName)
                    }
                  } else {
                    console.log('获取失败:' + response.data.message)
                    this.$message({
                      message: '获取失败:' + response.data.message,
                      type: 'error'
                    })
                    return false
                  }
                })
              }
            } else {
              this.$http.get(this.$http.defaults.workRecordAPI + `api/config/getValueByKey?key=report-month`).then(response => {
                if (response.data.success === true) {
                  if (response.data.result === '') {
                    this.$message({
                      message: '未开启填报！',
                      type: 'error'
                    })
                  // 应增加下发时beginDate处理
                  } else {
                    if (this.myRole === 1) {
                      respUserName = localStorage.getItem('userTrueName')
                    } else {
                      respUserName = this.personList.find(item => item.id === this.editForm.respUserId).truename
                    }
                    this.editForm.beginDate = response.data.result + '-01'
                    this.savedata(respUserName)
                  // let beginDay = new Date(response.data.result.substr(0, 4), parseInt(response.data.result.substr(5, 2)) - 1, 1)
                  // let endDay = new Date(response.data.result.substr(0, 4), parseInt(response.data.result.substr(5, 2)), 0)
                  // let sBeginText = this.editForm.limitDate[0]
                  // let sEndText = this.editForm.limitDate[1]
                  // let sBeginDay = new Date(sBeginText.substr(0, 4), parseInt(sBeginText.substr(5, 2)) - 1, sBeginText.substr(8, 2))
                  // let sEndDay = new Date(sEndText.substr(0, 4), parseInt(sEndText.substr(5, 2)) - 1, sEndText.substr(8, 2))
                  // console.log(beginDay + '|' + endDay)
                  // console.log(this.editForm.limitDate[0] + '|' + this.editForm.limitDate[1])
                  // if (sEndDay < beginDay || sBeginDay > endDay) {
                  //   console.log('超出本月')
                  //   this.$confirm('您填写的预计完成时限不在当前填报月内（' + response.data.result + '），确定要提交保存吗', '提示', {
                  //     type: 'success'
                  //   }).then(() => {
                  //     this.savedata(respUserName)
                  //   })
                  // } else {
                  //   console.log('未超出本月')
                  //   this.savedata(respUserName)
                  // }
                  }
                } else {
                  console.log('获取失败:' + response.data.message)
                  this.$message({
                    message: '获取失败:' + response.data.message,
                    type: 'error'
                  })
                  return false
                }
              })
            }
          }
        }
      })
    },
    getFormatDate (date) {
      var seperator1 = '-'
      var month = date.getMonth() + 1
      var strDate = date.getDate()
      if (month >= 1 && month <= 9) {
        month = '0' + month
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = '0' + strDate
      }
      var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
      return currentdate
    },
    savedata (respUserName) {
      let userArr = []
      if (this.editForm.otherRespUserIds && this.editForm.otherRespUserIds.length > 0) {
        userArr = this.unitList.filter(item => this.editForm.otherRespUserIds.indexOf(item.userId) > -1)
      }
      let arr = []
      if (userArr && userArr.length > 0) {
        userArr.forEach(item => {
          arr.push({respDept: item.deptName, respUserName: item.userName, respUserId: item.userId})
        })
      }
      let otherRespUsers = this.editForm.respDept === '司领导' ? arr : []
      let state = this.myRole
      if (this.isDown) {
        state = 6
      }
      if (this.isAdmin) {
        state = 4
        otherRespUsers = this.allUserList.filter(item => this.adminRespUsers.indexOf(item.id) > -1 && item.id !== this.editForm.respUserId).map(item => { return {respDept: item.unitname, respUserId: item.id, respUserName: item.truename} })
      }
      let para = {
        id: this.editForm.id,
        beginDate: this.editForm.beginDate,
        endDate: this.editForm.endDate,
        workPlan: this.editForm.workPlan,
        workType: this.editForm.workType,
        content: this.editForm.content,
        respDept: this.editForm.respDept,
        respUserId: this.editForm.respUserId,
        respUserName: respUserName,
        state: state,
        remarks: this.editForm.remarks,
        respUsers: otherRespUsers,
        hasOtherRespUser: otherRespUsers.length > 0
      }
      this.saveloading = true
      let url = 'api/record/saveRecord'
      this.$http
        .post(this.$http.defaults.workRecordAPI + url, para)
        .then(response => {
          this.saveloading = false
          if (response.data.success) {
            this.editFormReset()
            this.$emit('dialogHide', true)
            this.$message({
              message: '保存成功！',
              type: 'success'
            })
          } else {
            this.$message({
              message: '保存失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          this.saveloading = false
          console.log(error)
          this.$message({
            message: '网络保存失败:' + error,
            type: 'error'
          })
        })
    },
    editFormReset () {
      this.editForm = {
        id: null,
        beginDate: '',
        endDate: '',
        workPlan: '',
        workType: '',
        content: '',
        respDept: localStorage.getItem('unitName'),
        respUserId: null,
        respUserName: localStorage.getItem('userTrueName'),
        remarks: ''
      }
      if (this.$refs['editForm']) {
        this.$refs['editForm'].resetFields()
      }
      this.adminRespUsers = []
      // this.files = []
      // this.fileList = []
      // if (this.$refs.upload) {
      //   this.$refs.upload.clearFiles()
      // }
    },
    getDetail (id) {
      this.pageLoading = true
      this.$http
        .get(this.$http.defaults.workRecordAPI + `api/record/getDetailById?id=` + id)
        .then(response => {
          this.editForm = response.data.result
          // this.editForm.id = this.editForm.id
          console.log(this.editForm.respUsers ? this.editForm.respUsers.map(item => item.respUserId) : [])
          this.editForm.otherRespUserIds = this.editForm.respUsers ? this.editForm.respUsers.map(item => item.respUserId) : []
          if (this.isAdmin) {
            this.adminRespUsers = []
            if (this.editForm.respUserId) {
              this.adminRespUsers.push(this.editForm.respUserId)
            }
            this.adminRespUsers.push(...this.editForm.respUsers.map(item => item.respUserId))
            this.adminRespUsers = [...new Set(this.adminRespUsers)]
            if (!this.editForm.respUserId) {
              this.editForm.respUserId = -1
            }
          }
          this.pageLoading = false
        })
        .catch(error => {
          this.$message({
            message: '网络获取失败:' + error,
            type: 'error'
          })
        })
      this.$http
        .get(this.$http.defaults.workRecordAPI + `api/record/getCurrentUserId`)
        .then(response => {
          this.myUserId = response.data.result
        })
        .catch(error => {
          this.$message({
            message: '网络获取失败:' + error,
            type: 'error'
          })
        })
    },
    checkRoles () {
      if (localStorage.getItem('Roles').indexOf('ROLE_banshirenyuan') > -1) {
        this.myRole = 1
      }
      if (localStorage.getItem('Roles').indexOf('ROLE_chuzhang') > -1) {
        this.myRole = 2
      }
      if (localStorage.getItem('Roles').indexOf('ROLE_fusizhang') > -1) {
        this.myRole = 3
      }
      if (localStorage.getItem('Roles').indexOf('ROLE_sizhang') > -1) {
        this.myRole = 4
      }
      this.unitName = localStorage.getItem('unitName')
      if (this.unitName === '综合处' && this.myRole === 2) {
        this.isWorkRecordAdmin = true
      } else {
        this.isWorkRecordAdmin = false
        this.$http
          .get(this.$http.defaults.workRecordAPI + `api/manageuser/getCurrentIfManageUser`)
          .then(response => {
            if (response.data.success) {
              this.isWorkRecordAdmin = response.data.result
            } else {
              this.$message({
                message: '获取失败:' + response.data.message,
                type: 'error'
              })
            }
          })
          .catch(error => {
            if (error.status === 500) {
              this.$message({
                message: '网络获取失败:' + error,
                type: 'error'
              })
            }
          })
      }
    },
    getDeptList () {
      if ((this.myRole && this.myRole !== 1) || (this.isAdmin || this.isDown)) { // 处长执行此接口会自动取处长用户作为默认责任人，所以普通处内人员不要执行此方法，但综合处授权日志管理员需要执行
      // 查看全部处长上报情况，通过此接口也可获取处室列表
        this.$http.post(this.$http.defaults.workRecordAPI + `api/record/queryCzReportList`, {}).then(response => {
          if (response.data.success === true) {
            this.unitList = response.data.result // 获取处室列表
            if (!this.isAdmin) {
              this.editForm.respDept = localStorage.getItem('unitName')
              let myUnit = this.unitList.find(item => item.deptName === this.editForm.respDept)
              this.editForm.respUserId = myUnit ? myUnit.userId : ''
              this.editForm.respUserName = myUnit ? myUnit.userName : ''
            }
            if (this.projectId && this.projectId !== '') {
              this.getDetail(this.projectId)
            } else {
              this.pageLoading = false
            }
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
      }
    }
  },
  mounted () {
    this.checkRoles()
    this.getDics('01', 'workTypeList')
    this.init()
  }
}
</script>
<style>
  .wboxd .el-table th{
    font-weight: normal;
    background-image: linear-gradient(to bottom , #f8f8f8, #efefef);
  }
  .wboxd .el-table td, .el-table th{
    padding:0;
    font-size:var(--size14) !important;
    line-height: 20px;
    font-family: '宋体'
  }
#assessdetail .el-upload-list__item{
  width: 250px;
}
#assessdetail a{
  width: 200px;
}
.assessdetail .el-tabs__header{
  height: 29px;
  background: #FAFAFA;
  line-height: 30px;
  font-family: '宋体';
  padding:0 20px;
  border-bottom: 2px solid #E4E7ED;
  margin:0;
}
.assessdetail .el-tabs__item{
  line-height: 30px;
  height: 30px;
  font-weight:bolder;
}
  .cardtab .el-tabs__header{
    padding:0 !important;
    border-bottom:1px solid #E4E7ED;
  }
  #assessdetail .wboxs{
    height:45px;
    padding-top:0;
    margin-bottom: 10px;
  }
  .wboxs{
    padding:5px 15px;
    width: calc(100% - 30px);
    background: #fff;
    border: 1px solid #95B8E7;
    margin:0 10px;
    overflow: hidden;
  }
</style>

<style scoped>
  .tickettable th{
    font-weight:lighter;
    background-image: linear-gradient(to bottom , #f8f8f8, #efefef);
    text-align: center;
  }
  .tickettable{
    width: 100%;
    border-left: 1px solid #95B8E7;
    border-top: 1px solid #95B8E7;
  }
  .tickettable td, .tickettable th{
    padding:5px 10px;
    margin:0;
    font-size:var(--size14) !important;
    line-height: 20px;
    font-family: '宋体';
    border-bottom: 1px solid #95B8E7;
    border-right: 1px solid #95B8E7;
  }
  .tickettable td{
    vertical-align: middle;
    text-align: center;
    font-weight: bolder;
  }
  .mytable{
    border-top: 1px solid #74a6cc;
    border-left: 1px solid #74a6cc;
    margin:0 10px 10px;
    width: calc(100% - 20px);
  }
  .mytable th{
    padding: 10px;
    border-right: 1px solid #74a6cc;
    border-bottom: 1px solid #74a6cc;
    vertical-align: top;
    line-height: 150%;
    background: #FAFAFA;
    width:200px;
    text-align:right;
  }
  .mytable td{
    padding: 10px;
    border-right: 1px solid #74a6cc;
    border-bottom: 1px solid #74a6cc;
    vertical-align: top;
    line-height: 150%;
  }
  .wboxd{
    padding:0;
    width: calc(100% - 20px);
    background: #fff;
    border: 1px solid #95B8E7;
    margin:0 10px;
    overflow: hidden;
  }
</style>
